<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Virtual Functions</title>
  <meta
 content="C++ Tutorial: Virtual Functions, Pure Virtual Functirons"
 name="description" />
  <meta
 content="C++ Tutorial, Virtual Functions, Virtual Destructors,
 Virtual Methods, Virtual Constructors, Pure Virtual Functions, Pure Virtual Destructor, Name Hiding"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<br />
<div id="contenttext">

<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>

<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial - Virtual Functions</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>

<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>

</ul>
</div>

<br />
<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="VirtualFunctions">Virtual Functions</div>
<br />
<br />
<img src="images/virtual/class_inheritance_diagram.png" alt="class_inheritance_diagram"/>
<br />
<br />
<p>When we talk about <strong>virtual function</strong> or <strong>virtual method</strong>,
 it's always in the context of <strong>inheritance</strong> and <strong>polymorphism</strong>. 
 It is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature. 
In other words, the purpose of virtual functions is to allow customization of derived class implementations.</p>
<p>A virtual method is a method whose implementation is determined at runtime based on the actual type of the invoking object. 
It needs to be declared with the <strong>virtual</strong> keyword, and the <strong>nonvirtual</strong> method is the default.</p>
<p>In other words, defining in a base class a virtual function that has another version in a derived class signals to the compiler, 
<strong>"We don't want static binding for this function. 
What we do want is the selection of the function to be called at any given point in the program based on the kind of 
<font color="red">object</font> for which is called."</strong></p>
<br />
<br />

<div class="subtitle" id="DynamicBinding">Virtual Member Functions and Dynamic Binding</div>
<p>Let's look at our simple examples.</p>
<br />

<div class="subtitle_2nd" id="virtualexample1">Virtual Method Example 1</div>
<pre>
#include &lt;iostream&gt;

class A {
public:
	void f() { 
		std::cout << "A::f()" << std::endl;
	}
};

class B: public A {
public:
	void f() { 
		std::cout << "B::f()" << std::endl;
	}
};

class C: public B {
public:
	void f() { 
		std::cout << "C::f()" << std::endl;
	}
};

int main()
{
	A *a = new A(); 
	B *b = new B(); 
	C *c = new C();

	a->f();			// A::f()
	b->f();			// B::f()
	c->f();			// C::f()

	((B *)c)->f();		// B::f()
	((A *)c)->f();		// A::f()
	((A *)b)->f();		// A::f()

	return 0;
}
</pre>
<p>Because <strong>f()</strong> is declared as <strong>nonvirtual</strong>, the invoked method depends on the type used at <strong>compile time</strong>. So, the invoked methods are the method of the pointer types:</p>
<pre>
((B *)c)->f(); 
</pre>
<p><strong>c</strong> is a type of <strong>B</strong>, so it invokes the method of Class B and so on. </p>
<br />

<div class="subtitle_2nd" id="virtualexample2">Virtual Method Example 2</div>
<p>If we redeclare <strong>f()</strong> as virtual in the base class A as the code below:</p>
<pre>
#include &lt;iostream&gt;

class A {
public:
	virtual void f() { 
		std::cout << "A::f()" << std::endl;
	}
};

class B: public A {
public:
	void f() { 
		std::cout << "B::f()" << std::endl;
	}
};

class C: public B {
public:
	void f() { 
		std::cout << "C::f()" << std::endl;
	}
};

int main()
{
	A *a = new A(); 
	B *b = new B(); 
	C *c = new C();

	a->f();			// A::f()
	b->f();			// B::f()
	c->f();			// C::f()

	((B *)c)->f();		// C::f()
	((A *)c)->f();		// C::f()
	((A *)b)->f();		// B::f()

	return 0;
}</pre>
<p>then, the method invoked when we run is the method of the actual <strong>object</strong></p>
<pre>
((B *)c)->f();
</pre>
<p>So, because <strong>c</strong> is object type of Class C, it calls the <strong>f()</strong> in Class C,  <strong>C::f()</strong>.</p>

<br />

<div class="subtitle_2nd" id="virtualexample3">Virtual Method Example 3</div>
<pre>
class Base {
public:
	void f();
	virtual void vf();
};

class Derived : public Base {
public:
	void f();
	void vf();
};

#include &lt;iostream&gt;
using namespace std;

void Base::f() {
	cout << "Base f()" << endl;
}

void Base::vf() {
	cout << "Base vf()" << endl;
}

void Derived::f() {
	cout << "Derived f()" << endl;
}

void Derived::vf() {
	cout << "Derived vf()" << endl;
}

int main()
{
	Base b1;
	Derived d1;
	b1.f();
	b1.vf();
	d1.f();
	d1.vf();

	Derived d2;  	// Derived object
	Base* bp = &d2; // Base pointer to Derived object
	bp->f();	// Base f()
	<i><font color="red">bp->vf();</font></i>	// which vf()?

	return 0;
}
</pre>
<p>The output of the run is:</p>
<pre>
Base f()
Base vf()
Derived f()
Derived vf()
Base f()
<i><font color="red">Derived vf()</font></i>
</pre>
<p>The pointer (or reference) type is known at compile time while object type might be determined at runtime. Interpreting a function call in the source code as executing a particular block of function code is called <strong>binding</strong> the function name. </p>
<p>Binding that takes place during compile time is <strong>static binding</strong> or <strong>early binding</strong>. With the virtual function, the binding task is more difficult. The decision of which function to use can't be made at compile time because the compiler doesn't know which object the user is going to choose to make.</p>
<p>So, the compiler has to generate code that allows the <strong>correct</strong> virtual method to be selected as the code runs. This is <strong>dynamic binding</strong> or <strong>late binding</strong>.</p>
<p>In other words, when a request (message) is sent to an object, the particular operation that's performed depends on <strong>both</strong> the request <strong>and</strong> receiving object. Different objects that support identical request may have different implementation of the operations that fulfill these requests. The run-time association of a <strong>request</strong> to an object and one of its <strong>operations</strong> is known as <strong>dynamic binding</strong>. This means that issuing a request doesn't commit us to a particular implementation until run-time. So, we can write programs that expect an object with a particular interface, knowing that any object that has the correct interface will accept the request.</p>
<p>Let's look at the output we got. </p>
<p>Other results are as we expected. But the last one is the one that we want to talk more.</p>
<p>If <strong>vf()</strong> is not declared as <strong>virtual</strong> in the base class, <strong>bp->vf()</strong> goes by the pointer type (<strong>Base *</strong>) and invokes <strong>Base::vf()</strong>.</p>
<p>The pointer type is known at compile time as we discussed above, so the compiler can bind <strong>vf()</strong> to <strong>Base::vf()</strong> at compile time. In other words, the compiler uses <strong>static binding</strong> for <strong>nonvirtual</strong> method.</p>
<p>However, if <strong>vf()</strong> is declared as virtual in the base class, <strong>bp->vf()</strong> goes by the object type, here, <strong>Derived</strong> and invokes <strong>Derived::vf()</strong>.</p>
<p>In this example, we can see that the object type is <strong>Derived</strong>, however, there are cases the object type can only be determined at runtime. So, the compiler generated code that binds <strong>vf()</strong> to <strong>Base::vf()</strong> or <strong>Derived::vf()</strong>, depending on the object type at runtime.</p>
<p>In other words, the compiler uses <strong>dynamic binding</strong> for <strong>virtual</strong> methods.</p>
<p>In our example, <strong>vf()</strong> is virtual and the object type is <strong>Derived</strong>. So, it calls <strong>vf()</strong> in the <strong>Derived</strong> class.</p>
<p>Here is a summary for the virtual methods.</p>
<ul>
	<li>A virtual method in a base class makes the function virtual in all classes derived from the base class.</li>
	<li>If a virtual method is invoked by using a <strong>reference</strong> to an object or by using a <strong>pointer</strong> to an object, the code uses the method defined for the object type rather than the method defined for the reference or pointer type. This is <strong>dynamic binding</strong> or <strong>late binding</strong>.<br />
This behavior is important since it's always valid for a base-class pointer or reference to refer to an object of a derived type.</li>
	<li>If we're defining a class that will be used as a base class, we should declare as virtual functions the class methods that may have to be redefined in derived classes.</li>
	<li>The run-time selection is the primary advantage of virtual method.</li>
	<li>The disadvantages are that it takes longer to invoke a virtual method and that extra memory is required to store the information needed for the lookup.</li>
</ul>
<br />
<br />


<div class="subtitle" id="VirtualDestructor">Virtual Destructor</div>
<p>If a class to be used as a base class, the destructor should be <strong>virtual</strong>. 
If a class does not contain virtual functions, that often tells it is not meant to be used as a base class.</p>
<p>Calling a method with an object pointer always invokes:</p>
<ul>
	<li>The most derived class function, if a method is virtual.</li>
	<li>The function implementation corresponding to the object pointer type (used to call the method), if a method is not virtual.	</li>
</ul>
<p>A virtual destructor works in the same way. A destructor gets called when an object goes out of scope or when we call delete on an object pointer (reference).</p>
<p>When any derived class object goes out of scope, the destructor of that derived class gets called first. It then calls its parent class destructor so memory allocated to the object is properly released.</p>
<p>But, if we call delete on a base pointer which points to a derived class object, the base class destructor get called first for non-virtual function as in the example below.</p>
<br />
<div class="subtitle_2nd" id="VDExample1">Example 1</div>
<pre>
#include &lt;iostream&gt;

using namespace std;

class Base
{
public:
	Base() {
		cout << "Base Constructor \n" ;
	}
	<font color="red">~Base() {
		cout << "Base Destructor \n" ;
	}</font>
};

class Derived : public Base
{
public:
	Derived(string s):str(s) {
		cout << "Derived Constructor \n" ;
	}
	~Derived() {
		cout << "Derived Destructor \n" ;
	}
private:
	string str;
};

int main()
{
	Base *pB = new Derived("derived");
	delete pB;
}
</pre>
<p>Output from the run is:</p>
<pre>
Base Constructor
Derived Constructor
Base Destructor
</pre>
<p>As we see from the output, deleting a base pointer only calls destructor for the base class not the destructor for the derived class.</p>
<pre>
	Base *pB = new Derived();
	delete pB;
</pre>
<p>In the code, <strong>pB</strong> is a pointer to a base class with non-virtual destructor, and we are trying to delete a derived
class object through a base class pointer. The results are undefined. What happens at runtime is that the derived parts of the
object never destroyed. But the base class part typically would be destroyed. So, it has a weird object which is <strong>partially destroyed</strong>.</p> </p>
<p>However, if we declare the vase class destructor as virtual, this makes all the derived class destructors virtual as well. </p>
<p>Let's replace the above destructor:</p>
<pre>
	~Base() {
		cout << "Base Destructor \n" ;
	}
</pre>
<p>with this:</p>
<pre>
	<font color="red">virtual ~Base() {
		cout << "Base Destructor \n" ;
	}</font>
</pre>
<p>Then, the output becomes:</p>
<pre>
Base Constructor
Derived Constructor
<font color="red">Derived Destructor</font>
Base Destructor
</pre>


<br />
<br />
<div class="subtitle_2nd" id="VDExample2">Example 2</div>
<pre>
#include &lt;iostream&gt;

using namespace std;

class Base{
protected:
	int myInt;

public:
	Base(int n):myInt(n){
		cout << "Base Ctor\n";
	}
	virtual void print() const = 0;
	<font color="red">virtual</font> ~Base(){
		cout << "Base Dtor" << endl;
	}
};

class Derived: public Base {
public:	
	Derived(int n = 0):Base(n)  {
		str = new char[100];
		myInt = n;				
		cout << "Derived Ctor myInt" << endl;
	}
	void print()const{
		cout << "Derived print(): myInt = "<< myInt << endl;
	}

	~Derived(){
		cout << "Derived Dtor" << endl;
		delete [] str;
	}
private:
	char *str;
};


int main()
{
	Base *pB = new Derived(2010);
 	pB->print();
	delete pB;
	return 0;
}
</pre>
<p>In the example above, the <strong>Derived</strong> class has a <strong>char *</strong> member <strong>str</strong> that points to memory allocated by <strong>new</strong>. </p>
<pre>
str = new char[100];
</pre>
<p>Then, when a <strong>Derived</strong> object expires or we call <strong>delete</strong> on the pointer to the <strong>Derived</strong> object, it's critical that the <strong>~Derived</strong> destructor be called to free that memory.</p> 
<pre>
Derived::~Derived(){
	delete [] str;
}
</pre>
<p>The output from the run:</p>
<pre>
Base Ctor
Derived Ctor myInt
Derived print(): myInt = 2010
Derived Dtor
Base Dtor
</pre>
<br />
<br />
<p>Look at the line of code below</p>
<pre>
delete pB;
</pre>
<p>If the default static binding applies, the <strong>delete</strong> invokes the <strong>Base</strong> destructor, <strong>~Base()</strong>.</p> 
<p>This frees memory pointed to by the <strong>Base</strong> component of the <strong>Derived</strong> object but not memory pointed to by the new class members. </p>
<p>However, if the destructors are <strong>virtual</strong>, the same code invokes the <strong>~Derived()</strong> destructor, which frees memory pointed to by the <strong>Derived</strong> component, and then calls the <strong>~Base()</strong> destructor to free memory pointed to by the <strong>Base</strong> component.</p>
<p>So, using virtual destructors ensures that the <strong>correct sequence</strong> of destructors is called.</p>
<br />
<br />


<div class="subtitle" id="VirtualConstructor">Virtual Constructor</div>
<p>Constructors can't be virtual. </p>
<p>Creating a derived object invokes a derived class constructor, not a base class constructor. The derived class constructor then uses a base class constructor, but the sequence is distinct from the inheritance mechanism. Therefore, a derived class doesn't inherit the base class constructors, so usually there's not much point to making them virtual, anyway.</p>

<br />
<br />


<div class="subtitle" id="PureVirtual">Pure Virtual Functions</div>
<p>If we change the virtual function in the <strong>Base</strong> class:</p>
<pre>
virtual void vf();
</pre>
<p>to: </p>
<pre>
virtual void vf() = 0;
</pre>
<p>the <strong>vf()</strong> becomes a <strong>pure</strong> virtual function.</p>
<p>Suddenly, the <strong>Base</strong> class becomes an <strong>abstract</strong> class. Its <strong>pure virtual function, vf()</strong> marks it as such.</p>
<p>As a result, clients cannot create instances of the <strong>Base</strong> class, only of classes derived from it.</p>
<p>Here is a little summary for the purpose of virtual functions from <strong>Effective C++</strong> by Scott Meyers.</p> 
<ul>
	<li>The purpose of declaring a <strong>pure virtual function</strong> is to have derived classes inherit a function <strong>interface only</strong>.</li>
	<li>On the other hands, the purpose of declaring a <strong>simple virtual function</strong> is to have derived classes inherit a function <strong>interface as well as a default implementation</strong>.</li>
	<li>The purpose of declaring a <strong>non-virtual function</strong> is to have derived classes inherit a function <strong>interface as well as a mandatory implementation</strong>.</li>
</ul>

<br />
<br />


<div class="subtitle" id="PureVirtualDestructor">Pure Virtual Destructor</div>
<br />
<ul>
	<li><strong>We must provide a function body for the pure virtual destructor.</strong><br />
<p>While pure virtual destructors are legal in Standard C++, there is
an added constraint when using them: <br />
we must provide a <strong>function body</strong> for the pure virtual destructor. <br />
This seems counterintuitive; how can a virtual function be <strong>pure</strong> if it needs a function body?<br />
But if we keep in mind that constructors and destructors are
special operations it makes more sense, especially if we remember
that all destructors in a class hierarchy are always called. 
If we do not provide the definition for a pure virtual destructor, what function body would be called during destruction? <br />
Thus, it's absolutely necessary that the compiler and linker enforce the existence of a function body for a pure virtual destructor.
<pre>
//Interface.h 

class Interface {
public:
	//pure virtual destructor declaration
	virtual ~Interface() = 0; 
};
</pre>
<p>
Then, somewhere outside the class declaration, the pure virtual destructor has to be defined like this: </p>
<pre>
//Interface.cpp file

//definition of a pure virtual destructor; should always be empty
Interface::~Interface() {} 
</pre>
</li>
	<li><strong>What's the value of it? </strong><br />
If it's pure, but it has to have a function body, what's the value of it? <br />
The only difference you'll see between the pure and non-pure
virtual destructor is that the pure virtual destructor does cause the
base class to be abstract, so you cannot create an object of the base
class. </li>
	<br />
	<li><strong>Difference between a regular virtual destructor and a pure virtual destructor.</strong><br />
So what's the difference between a regular virtual destructor and a pure virtual destructor?<br />
The only distinction occurs when you have a class that only has a single pure virtual function: the destructor. In this case, the only effect of the purity of the destructor is to prevent the instantiation of the base class. <br />
If there were any other pure virtual functions, they would prevent the instantiation of the base class, but if there are no others, then the pure virtual destructor will do it. <br />
	</li>
</ul>

<br />
<br />


<div class="subtitle" id="costofvirtual">The Costs of Virtual Functions</div>
<p>Using <strong>virtual functions</strong> has the following costs in memory and execution speed:</p>
<ul>
	<li>Each object has its size increased by the amount needed to hold an address.</li>
	<li>For each class, the compiler creates a table of addresses of virtual functions.</li>
	<li>For each function call, there is an extra step of looking up the address on the table.</li>
</ul>

<br />
<br />


<div class="subtitle" id="namehiding">Name Hiding</div>
<p>Let's look at the following example:</p>
<pre>
#include &lt;iostream&gt;

using namespace std;

class Base 
{	
public:
	virtual void MethodA() {
		cout << "Base::void MethodA()" << endl;
	}
	virtual void MethodA(int a) {
		cout << "Base::void MethodA(int a)" << endl;
	}
};

class Derived : public Base
{
public:
	virtual void MethodA() {
		cout << "Derived::void MethodA()" << endl;
	}
};

int main() 
{
	Derived d;
	d.MethodA();
	d.MethodA(4);
	return 0;
}
</pre>
<p>We may get a compiler error something like this:</p>
<pre>
'Derived::MethodA' : function does not take 1 arguments
</pre> 
<p>Even though we may not get the error, however, the code has the following implications:</p>
<pre>
Derived d;
d.MethodA();	// OK
d.MethodA(4);	// Not OK
</pre>
<p>The new definition defines a <strong>MethodA()</strong> that takes no arguments. Rather than resulting in two overloaded version of the function, this redefinition <strong>hides</strong> the base class version that takes an int argument. In other words, redefining inherited methods is not a variation of overloading. If we redefine a function in a derived class, it doesn't just override the base class declaration with the same function signature. It <strong>hides all</strong> base-class methods of the <strong>same name</strong>, regardless of the argument signature.</p>
<p>So, if the base class declaration is overloaded, we need to redefine all the base-class versions in the derived class as in the modified code below:</p>
<pre>
#include &lt;iostream&gt;

using namespace std;

class Base 
{	
public:
	virtual void MethodA() {
		cout << "Base::void MethodA()" << endl;
	}
	virtual void MethodA(int a) {
		cout << "Base::void MethodA(int a)" << endl;
	}
};

class Derived : public Base
{
public:
	virtual void MethodA() {
		cout << "Derived::void MethodA()" << endl;
	}
	<font color="red">virtual void MethodA(int a) {
		cout << "Derived::void MethodA(int a)" << endl;
	}</font>
};

int main() 
{
	Derived d;
	d.MethodA();
	d.MethodA(4);
	return 0;
}
</pre>
<p>Now, we have an output:</p>
<pre>
Derived::void MethodA()
Derived::void MethodA(int a)
</pre>
<p>If we redefine just one version, the other one become hidden and cannot be used by objects of the derived class. </p>
<br /><br />

<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />




<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
